package com.lexue.articlesync.controller;

import com.lexue.articlesync.service.ToutiaoCookiesService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 头条号Cookies管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/toutiao/cookies")
@RequiredArgsConstructor
public class ToutiaoCookiesController {
    
    private final ToutiaoCookiesService toutiaoCookiesService;
    
    /**
     * 自动检测并获取头条登录cookies
     */
    @PostMapping("/detect")
    public ResponseEntity<Map<String, Object>> detectCookies() {
        try {
            ToutiaoCookiesService.CookiesResult result = toutiaoCookiesService.detectAndGetCookies();
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", result.isSuccess());
            response.put("message", result.getMessage());
            
            if (result.isSuccess()) {
                response.put("cookies", result.getCookies());
                response.put("userInfo", result.getUserInfo());
                response.put("obtainedAt", result.getObtainedAt());
            } else if (result.getInstruction() != null) {
                response.put("instruction", result.getInstruction());
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("检测头条cookies失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "检测失败: " + e.getMessage());
            return ResponseEntity.ok(errorResponse);
        }
    }
    
    /**
     * 验证提供的cookies是否有效
     */
    @PostMapping("/validate")
    public ResponseEntity<Map<String, Object>> validateCookies(@RequestBody ValidateCookiesRequest request) {
        try {
            ToutiaoCookiesService.CookiesValidationResult result = 
                toutiaoCookiesService.validateCookiesWithUserInfo(request.getCookies());
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", result.isSuccess());
            response.put("valid", result.isValid());
            response.put("message", result.getMessage());
            
            if (result.isValid() && result.getUserInfo() != null) {
                response.put("userInfo", result.getUserInfo());
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("验证头条cookies失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "验证失败: " + e.getMessage());
            return ResponseEntity.ok(errorResponse);
        }
    }
    
    /**
     * 获取手动获取cookies的指导说明
     */
    @GetMapping("/instruction")
    public ResponseEntity<Map<String, Object>> getCookiesInstruction() {
        ToutiaoCookiesService.CookiesResult result = toutiaoCookiesService.getCookiesFromBrowser();
        
        Map<String, Object> response = new HashMap<>();
        response.put("success", true);
        response.put("instruction", result.getInstruction());
        
        return ResponseEntity.ok(response);
    }
    
    /**
     * 检查头条登录状态
     */
    @GetMapping("/login-status")
    public ResponseEntity<Map<String, Object>> checkLoginStatus() {
        try {
            ToutiaoCookiesService.CookiesResult result = toutiaoCookiesService.detectAndGetCookies();
            
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("loggedIn", result.isSuccess());
            response.put("message", result.getMessage());
            
            if (result.isSuccess() && result.getUserInfo() != null) {
                response.put("userInfo", result.getUserInfo());
            }
            
            return ResponseEntity.ok(response);
            
        } catch (Exception e) {
            log.error("检查头条登录状态失败", e);
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("loggedIn", false);
            errorResponse.put("message", "检查失败: " + e.getMessage());
            return ResponseEntity.ok(errorResponse);
        }
    }
    
    /**
     * 验证cookies请求DTO
     */
    public static class ValidateCookiesRequest {
        private String cookies;
        
        public String getCookies() {
            return cookies;
        }
        
        public void setCookies(String cookies) {
            this.cookies = cookies;
        }
    }
}